package org.shop.controller.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Goods;
import org.shop.entity.HotSearch;
import org.shop.entity.ShufflingInstall;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.GoodsService;
import org.shop.service.HotSearchService;
import org.shop.service.ShufflingInstallService;
import org.shop.service.redis.RedisService;
import org.shop.util.JsonUtils;
import org.shop.util.ObjUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

@Controller
public class IndexController {
	
	private static final Class<Goods> Goods = null;

	private static final Class ShufflingInstall = null;

	private static Logger logger = LogManager.getLogger(IndexController.class);
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ShufflingInstallService shufflingInstallService;
	@Autowired
	private HotSearchService hotSearchService;
	@Autowired
	private RedisService redisService;

	/**
	 * app首页
	 * @param req
	 * @return
	 */
	@RequestMapping("app/appIndex")
	public String getIndex(HttpServletRequest req){
		try{
			
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, Object> paramMap = new HashMap<String, Object>();
			params.put("currentPage", 0);
			params.put("pageSize", 10);
			params.put("schoolId", (long)1);
			List<Goods> goodsList = new ArrayList<Goods>();
//			if(redisService.getString("goodsList") == null) {
				goodsList = goodsService.getUserGoodsList(params);
//				redisService.setString("goodsList", JsonUtils.toJson(goodsList)); 
//			}else {
//				goodsList = jsonToList(redisService.getString("goodsList"),Goods);
//			}
			
			Map<String, Object> params2 = new HashMap<String, Object>();
			params2.put("goodsIdentifying", 2);
			params2.put("currentPage", 0);
			params2.put("pageSize", 3);
			params2.put("schoolId", (long)1);
			List<Goods> usedGoodsList = goodsService.getUserGoodsList(params2);//获取所有二手
			Map<String, Object> params3 = new HashMap<String, Object>();
			params3.put("goodsIdentifying", 1);
			params3.put("currentPage", 0);
			params3.put("pageSize", 3);
			params3.put("schoolId", (long)1);
			List<Goods> newGoodsList = goodsService.getUserGoodsList(params3);//获取所有新品
			//获取轮播图
			paramMap.put("defaultState", 1);
			ShufflingInstall shufflingInstallInfo = shufflingInstallService.getShufflingInstallInfo(paramMap);
			req.setAttribute("goodsList", goodsList);
			req.setAttribute("usedGoodsList", usedGoodsList);
			req.setAttribute("newGoodsList", newGoodsList);
			req.setAttribute("shufflingInstallInfo", shufflingInstallInfo);
			
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/index";
	}
	
	/**
	 * app首页优选好物
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getIndexGoodsList")
	@ResponseBody
	public List<Goods> getIndexGoodsList(HttpServletRequest req){
		String currentPage = req.getParameter("currentPage");
		String pageSize = req.getParameter("pageSize");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("state", 2);//1：审核中，2：审核通过
		params.put("currentPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
		params.put("pageSize", pageSize);
		List<Goods> goodsList = new ArrayList<Goods>();
		goodsList = goodsService.getUserGoodsList(params);
		return goodsList;
	}
	
	/**
	 * 首页跳转搜索页面
	 * @param req
	 * @return
	 */
	@RequestMapping("app/search")
	public String search(HttpServletRequest req){
		Map<String, Object> hotParams = new HashMap<String, Object>();
		Map<String, Object> recentlyParams = new HashMap<String, Object>();
		//获取登录人用户信息
		MyUserDetail ud = null;
		if(ObjUtil.isNotNullAndEmpty(SecurityContextHolder.getContext().getAuthentication())) {
			ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		List<HotSearch>  recentlySearchList = null;
		try {
			hotParams.put("hotSearchType", 0);
			hotParams.put("hotSearch", "0");
			List<HotSearch>  hotSearchList= hotSearchService.getHotAndRecentlySearchResult(hotParams);
			if(ObjUtil.isNotNullAndEmpty(ud)) {
				recentlyParams.put("userId", ud.getUserId());
				recentlyParams.put("hotSearchType", 0);
				recentlyParams.put("recentlySearch", "0");
				recentlySearchList= hotSearchService.getHotAndRecentlySearchResult(recentlyParams);
			}else {
				recentlySearchList = null;
			}
			req.setAttribute("hotSearchList", hotSearchList);
			req.setAttribute("recentlySearchList", recentlySearchList);
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/search";
	}
	
	/**
	 * 首页搜索
	 * @param req
	 * @return
	 */
	@RequestMapping("app/indexSearch")
	public String indexSearch(HttpServletRequest req){
		String content = req.getParameter("content");
		//获取登录人用户信息
		MyUserDetail ud = null;
		if(ObjUtil.isNotNullAndEmpty(SecurityContextHolder.getContext().getAuthentication())) {
			ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		try{
			Map<String, Object> params = new HashMap<String, Object>();
			//一手搜索插入
			HotSearch hotSearch = new HotSearch();
			hotSearch.setHotSearchResult(content);
			hotSearch.setHotSearchType((byte) 0);
			if(ObjUtil.isNotNullAndEmpty(ud)) {
				hotSearch.setUserId(ud.getUserId());
			}
			//判断是否存在这个搜索
			HotSearch hotSearchJudge = hotSearchService.getHostSearchInfo(hotSearch);
			if(hotSearchJudge==null||"".equals(hotSearchJudge)) {
				//不存在就插入
				hotSearchService.insertSelective(hotSearch );
			}else {
				//如果存在就数量加一
				hotSearchJudge.setHotSearchCount((hotSearchJudge.getHotSearchCount()+1));
				hotSearchService.updateByPrimaryKeySelective(hotSearchJudge);
			}
			params.put("state", 2);//1：审核中，2：审核通过
			params.put("selectName", content);
			params.put("used", 1);
			params.put("schoolId", 	ud.getSchoolId());
			List<Goods> goodsList = goodsService.getUserGoodsList(params);
			req.setAttribute("goodsList", goodsList);
			req.setAttribute("content", content);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/searchResult";
	}
	
	/**
	 * 跳转二手搜索页面
	 * @param req
	 * @return
	 */
	@RequestMapping("app/searchTwoHand")
	public String searchTwoHand(HttpServletRequest req){
		Map<String, Object> hotParams = new HashMap<String, Object>();
		Map<String, Object> recentlyParams = new HashMap<String, Object>();
		//获取登录人用户信息
		MyUserDetail ud = null;
		if(ObjUtil.isNotNullAndEmpty(SecurityContextHolder.getContext().getAuthentication())) {
			ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		List<HotSearch>  recentlySearchList = null;
		try {
			hotParams.put("hotSearchType", 1);
			hotParams.put("hotSearch", "0");
			List<HotSearch>  hotSearchList= hotSearchService.getHotAndRecentlySearchResult(hotParams);
			if(ObjUtil.isNotNullAndEmpty(ud)) {
				recentlyParams.put("userId", ud.getUserId());
				recentlyParams.put("hotSearchType", 1);
				recentlyParams.put("recentlySearch", "0");
				recentlySearchList= hotSearchService.getHotAndRecentlySearchResult(recentlyParams);
			}else {
				recentlySearchList = null;
			}
			req.setAttribute("hotSearchList", hotSearchList);
			req.setAttribute("recentlySearchList", recentlySearchList);
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/searchTwoHand";
	}
	
	/**
	 * 二手商品和求购商品搜索
	 * @param req
	 * @return
	 */
	@RequestMapping("app/twoHandSearch")
	public String twoHandSearch(HttpServletRequest req) {
		String content = req.getParameter("content");
		//获取登录人用户信息
		MyUserDetail ud = null;
		if(ObjUtil.isNotNullAndEmpty(SecurityContextHolder.getContext().getAuthentication())) {
			ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		try{
			Map<String, Object> params = new HashMap<String, Object>();
			//一手搜索插入
			HotSearch hotSearch = new HotSearch();
			hotSearch.setHotSearchResult(content);
			hotSearch.setHotSearchType((byte) 1);
			if(ObjUtil.isNotNullAndEmpty(ud)) {
				hotSearch.setUserId(ud.getUserId());
			}
			//判断是否存在这个搜索
			HotSearch hotSearchJudge = hotSearchService.getHostSearchInfo(hotSearch);
			if(hotSearchJudge==null||"".equals(hotSearchJudge)) {
				//不存在就插入
				hotSearchService.insertSelective(hotSearch );
			}else {
				//如果存在就数量加一
				hotSearchJudge.setHotSearchCount((hotSearchJudge.getHotSearchCount()+1));
				hotSearchService.updateByPrimaryKeySelective(hotSearchJudge);
			}
			params.put("selectName", content);
			params.put("schoolId", 	ud.getSchoolId());
			params.put("goodsIdentifyingType", 	"2");
			List<Map<String, Object>> usedGoodsList = goodsService.getUsedGoodsList(params);
			req.setAttribute("usedGoodsList", usedGoodsList);
			req.setAttribute("content", content);
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/searchTwoHandResult";
	}
	
	
	/**
	 * 删除最近的搜索记录
	 * @param req
	 * @return
	 */
	@RequestMapping("app/delRecentlySearchOneResult")
	@ResponseBody
	public Map<String,Object> delRecentlySearchOneResult(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		String hotSearchIds = req.getParameter("hotSearchId");
		try {
			String[] idArray = hotSearchIds.split(",");
			for (String hotSearchId : idArray) {
				hotSearchService.deleteByPrimaryKey(Long.parseLong(hotSearchId));
			}
			map.put("num", 1);
		}catch(Exception e) {
			map.put("num", 0);
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	
}
	
	
